package service

import (
	"flag"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"im/helper"
	"im/models"
	"log"
	"net/http"
	"time"
)

var addr = flag.String("addr", "localhost:8080", "http service address")
var upgrader = websocket.Upgrader{}
var wc = make(map[string]*websocket.Conn)

func WebSocketMessage(c *gin.Context) {
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "WebSocket连接错误：" + err.Error(),
		})
		return
	}
	defer func(conn *websocket.Conn) {
		err := conn.Close()
		if err != nil {
			log.Println("Error:", err.Error())
		}
	}(conn)

	uc := c.MustGet("user_claims").(*helper.UserClaims)
	wc[uc.Identity] = conn

	//无限循环，持续监听客户端信息
	for {
		ms := new(models.Message)
		err := conn.ReadJSON(ms)
		if err != nil {
			log.Println("Read Errors:" + err.Error())
			return
		}
		// 判断用户是否属于消息体的房间
		_, err = models.GetUserRoomByUIDRID(uc.Identity, ms.RoomID)
		if err != nil {
			log.Printf("uc.id:%v,ms.id:%v \n", uc.Identity, ms.RoomID)
			log.Println("用户不在同一房间-Error:", err.Error())
			return
		}
		//保存信息
		mb := &models.MessageBasic{
			UserIdentity: uc.Identity,
			RoomIdentity: ms.RoomID,
			Data:         ms.Message,
			CreatedAt:    time.Now().Unix(),
			UpdatedAt:    time.Now().Unix(),
		}
		err = models.InsertOneMessageBasic(mb)
		if err != nil {
			log.Println("Error:", err.Error())
			c.JSON(http.StatusOK, gin.H{
				"code": -1,
				"msg":  "插入数据库错误 Error:" + err.Error(),
			})
			return
		}
		// 获取在特定房间的在线用户
		userRooms, err := models.GetUserRoomByRID(ms.RoomID)
		if err != nil {
			log.Println("Error:", err.Error())
			return
		}
		for _, room := range userRooms {
			if cc, ok := wc[room.UserIdentity]; ok {
				log.Println("msg:", ms.Message)
				err := cc.WriteMessage(websocket.TextMessage, []byte(ms.Message))
				if err != nil {
					log.Println("Error:", err.Error())
					return
				}
			}
		}
	}
}
